package com.beiing.tianshuai.tianshuai.home.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.activity.NewDiscoveryPublishActivity;
import com.beiing.tianshuai.tianshuai.activity.WebViewActivity;
import com.beiing.tianshuai.tianshuai.adapter.HomeRecyclerViewAdapter;
import com.beiing.tianshuai.tianshuai.adapter.HotActive_RVAdapter;
import com.beiing.tianshuai.tianshuai.app.HttpRequestConstant;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.dongtai.view.DynamicPublishActivity;
import com.beiing.tianshuai.tianshuai.entity.HomeBean;
import com.beiing.tianshuai.tianshuai.entity.IndexListBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.freshnews.DiscoveryDetailActivity;
import com.beiing.tianshuai.tianshuai.freshnews.view.DiscoveryActivity;
import com.beiing.tianshuai.tianshuai.home.presenter.HomePresenterImpl;
import com.beiing.tianshuai.tianshuai.home.view.IHomeView;
import com.beiing.tianshuai.tianshuai.huodong.ActivitiesDetailActivity;
import com.beiing.tianshuai.tianshuai.huodong.view.HuoDongActivity;
import com.beiing.tianshuai.tianshuai.interest.InterestPublishActivity;
import com.beiing.tianshuai.tianshuai.mine.ui.IdentificationStatusActivity;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.mine.ui.NewPersonalIndexActivity;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.widget.MyRefreshHeader;
import com.beiing.tianshuai.tianshuai.widget.RecycleViewDivider;
import com.beiing.tianshuai.tianshuai.widget.TranslucentScrollView;
import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener;
import com.tianshuai.easypopup.EasyPopup;
import com.tianshuai.easypopup.HorizontalGravity;
import com.tianshuai.easypopup.VerticalGravity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGABanner;

/**
 * Created by LZQ on 2017/9/22.
 */

public class HomeFragment extends BaseFragment implements IHomeView {

    private static final String TAG = "HomeFragment";

    private List<HomeBean.DataBean.HotActiveBean> hotActiveBeanList;

    private HotActive_RVAdapter hotActiveRvAdapter;

    private HomeRecyclerViewAdapter homeRvAdapter;

    private HomePresenterImpl mPresenter;

    private String uid = "";

    private int page = 2;

    private String leWuUrl = "http://lewu.tianshuai.com.cn/index.php/Home/index/app_index";

    private int retryConnectIndexDetail = 0;

    /**
     * Toolbar上发布按钮点击弹出的菜单
     */
    private EasyPopup mEasyPopup;

    /**
     * 声明AMapLocationClient类对象
     */
    public AMapLocationClient mLocationClient = null;

    /**
     * 声明定位回调监听器
     */
    public AMapLocationListener mLocationListener = new MyAMapLocationListener();

    /**
     * 声明AMapLocationClientOption对象
     */
    public AMapLocationClientOption mLocationOption = null;

    private List<IndexListBean> mIndexListBeans = new ArrayList<>();

    @BindView(R.id.tv_location)
    TextView mTvLocation;
    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.refresh_header)
    MyRefreshHeader mRefreshHeader;
    @BindView(R.id.home_banner)
    BGABanner mBanner;
    @BindView(R.id.home_active)
    TextView tvActive;
    @BindView(R.id.home_discovery)
    TextView tvDiscovery;
    @BindView(R.id.home_topic)
    TextView tvTopic;
    @BindView(R.id.tv_hot_active)
    TextView tvHotActive;
    @BindView(R.id.tv_more_active)
    TextView tvMoreActive;
    @BindView(R.id.rv_hot_active)
    RecyclerView rvHotActive;
    @BindView(R.id.iv_attestation)
    ImageView ivAttestation;
    @BindView(R.id.rv_recommend_content)
    RecyclerView rvRecommendContent;
    @BindView(R.id.tv_search_recommend)
    TextView tvSearchRecommend;
    @BindView(R.id.rv_search)
    RelativeLayout rvSearch;
    @BindView(R.id.btn_publish)
    ImageButton btnPublish;
    @BindView(R.id.home_toolbar)
    Toolbar mToolbar;
    @BindView(R.id.tsv_scroll_view)
    TranslucentScrollView mScrollView;
    @BindView(R.id.toolbar_underline)
    View mToolbarUnderLine;
    @BindView(R.id.view_split1)
    View viewSplit1;
    @BindView(R.id.view_split2)
    View viewSplit2;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void init(View mView) {
        initStatusBar();

        mEasyPopup = new EasyPopup(mContext)
                .setContentView(R.layout.menu_home_fragment_toolbar)
                .setAnimationStyle(R.style.QQPopAnim)
                .setFocusAndOutsideEnable(true)
                .createPopup();
        initEasyPopup();

        initData();
        initRecyclerView();
        initListener();
        initPresenter();
        initAMap();
    }

    private void initData() {
        uid = UserInfoBean.getUid(mContext);
        mBanner.setAdapter(new BGABanner.Adapter<ImageView, String>() {
            @Override
            public void fillBannerItem(BGABanner banner, ImageView itemView, String model, int position) {
                Glide.with(mContext)
                        .load(model)
                        .into(itemView);
            }
        });
    }

    private void initPresenter() {
        mPresenter = new HomePresenterImpl(this);
        mPresenter.getHomeContent(uid);
    }

    private void initStatusBar() {
//        QMUIStatusBarHelper.setStatusBarLightMode(getActivity());
//        QMUIStatusBarHelper.translucent(getActivity());
//        int statusBarHeight = QMUIStatusBarHelper.getStatusbarHeight(getActivity());
//        mToolbar.setPadding(0, statusBarHeight, 0, 0);
    }

    private void initRecyclerView() {
        //热门活动部分
        hotActiveBeanList = new ArrayList<>();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        hotActiveRvAdapter = new HotActive_RVAdapter(mContext, hotActiveBeanList);
        rvHotActive.setNestedScrollingEnabled(false);
        rvHotActive.setLayoutManager(linearLayoutManager);
        rvHotActive.addItemDecoration(
                new RecycleViewDivider(
                        mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0.5f),
                        ContextCompat.getColor(mContext, R.color.common_gray_background))
        );
        rvHotActive.setAdapter(hotActiveRvAdapter);

        //活动、发现、视频 混排部分
        homeRvAdapter = new HomeRecyclerViewAdapter(mContext, mIndexListBeans);
        LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false);
        rvRecommendContent.setLayoutManager(linearLayoutManager1);
        rvRecommendContent.setNestedScrollingEnabled(false);
        rvRecommendContent.addItemDecoration(
                new RecycleViewDivider(
                        mContext, LinearLayoutManager.HORIZONTAL, DensityUtils.dp2px(mContext, 0.5f),
                        ContextCompat.getColor(mContext, R.color.common_gray_background))
        );
        rvRecommendContent.setAdapter(homeRvAdapter);
    }

    private void initAMap() {
        //初始化定位
        mLocationClient = new AMapLocationClient(mContext.getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(true);

        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    @Override
    public void showHomeContent(HomeBean bean) {
        try {
            HomeBean.DataBean homeBean = bean.getData();
            List<HomeBean.DataBean.HotActiveBean> hotActiveBeans = homeBean.getHotActive();
            hotActiveBeanList.addAll(hotActiveBeans);
            hotActiveRvAdapter.notifyDataSetChanged();

            for (HomeBean.DataBean.ActiveBean active : homeBean.getActive()) {
                IndexListBean indexListBean = new IndexListBean();
                indexListBean.setId(active.getId());
                indexListBean.setType(active.getType());
                indexListBean.setCover(active.getCover());
                indexListBean.setActionTime(active.getActionTime());
                indexListBean.setExitTime(active.getExitTime());
                indexListBean.setTitle(active.getStrech());
                indexListBean.setUserAvatar(active.getPhoto());
                indexListBean.setUserName(active.getUname());
                indexListBean.setUserId(active.getUid());
                indexListBean.setViewCount(active.getView());
                mIndexListBeans.add(indexListBean);
            }
            for (HomeBean.DataBean.FreshBean freshBean : homeBean.getFresh()) {
                IndexListBean indexListBean = new IndexListBean();
                indexListBean.setId(freshBean.getId());
                indexListBean.setType(freshBean.getType());
                indexListBean.setCover(freshBean.getCover());
                indexListBean.setTime(freshBean.getCreateTime());
                indexListBean.setTitle(freshBean.getTitle());
                indexListBean.setUserAvatar(freshBean.getPhoto());
                indexListBean.setUserName(freshBean.getName());
                indexListBean.setUserId(freshBean.getUId());
                indexListBean.setViewCount(freshBean.getView());
                mIndexListBeans.add(indexListBean);
            }
            homeRvAdapter.notifyDataSetChanged();

            List<String> bannerPicUrls = new ArrayList<>();
            final List<String> bannerContentUrls = new ArrayList<>();
            for (HomeBean.DataBean.ActivePhotoBean i : bean.getData().getActivePhoto()) {
                bannerPicUrls.add(HttpRequestConstant.HOME_BANNER + i.getCover());
                bannerContentUrls.add(i.getUrl());
            }
            if (bannerPicUrls.size() > 1) {
                mBanner.setAutoPlayAble(true);
            } else {
                mBanner.setAutoPlayAble(false);
            }
            mBanner.setData(bannerPicUrls, null);
            mBanner.setDelegate(new BGABanner.Delegate() {
                @Override
                public void onBannerItemClick(BGABanner banner, View itemView, Object model, int position) {
                    if (!TextUtils.equals(bannerContentUrls.get(position), "")) {
                        if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                            startActivity(new Intent(mContext, LoginActivity.class));
                        } else {
                            Intent intent = new Intent(mContext, WebViewActivity.class);
                            intent.putExtra("url", bannerContentUrls.get(position));
                            startActivity(intent);
                        }
                    }
                }
            });

            switch (bean.getData().getUserAuth()) {
                case "1":
                case "2":
                case "3":
                case "4":
                    ivAttestation.setVisibility(View.GONE);
                    break;
                default:
                    ivAttestation.setVisibility(View.VISIBLE);
            }

            if (mRefreshLayout.isRefreshing() || mRefreshLayout.isLoading()) {
                mRefreshLayout.finishRefresh();
                mRefreshLayout.finishLoadmore();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void showHomeList(HomeBean bean) {
        HomeBean.DataBean homeBean = bean.getData();
        List<HomeBean.DataBean.ActiveBean> actives = homeBean.getActive();
        for (HomeBean.DataBean.ActiveBean active : actives) {
            IndexListBean indexListBean = new IndexListBean();
            indexListBean.setId(active.getId());
            indexListBean.setType(active.getType());
            indexListBean.setCover(active.getCover());
            indexListBean.setActionTime(active.getActionTime());
            indexListBean.setExitTime(active.getExitTime());
            indexListBean.setTitle(active.getStrech());
            indexListBean.setUserAvatar(active.getPhoto());
            indexListBean.setUserName(active.getUname());
            indexListBean.setUserId(active.getUid());
            indexListBean.setViewCount(active.getView());
            mIndexListBeans.add(indexListBean);
        }
        for (HomeBean.DataBean.FreshBean freshBean : homeBean.getFresh()) {
            IndexListBean indexListBean = new IndexListBean();
            indexListBean.setId(freshBean.getId());
            indexListBean.setType(freshBean.getType());
            indexListBean.setCover(freshBean.getCover());
            indexListBean.setTime(freshBean.getCreateTime());
            indexListBean.setTitle(freshBean.getTitle());
            indexListBean.setUserAvatar(freshBean.getPhoto());
            indexListBean.setUserName(freshBean.getName());
            indexListBean.setUserId(freshBean.getUId());
            indexListBean.setViewCount(freshBean.getView());
            mIndexListBeans.add(indexListBean);
        }
        homeRvAdapter.notifyDataSetChanged();
        page += 1;
        if (mRefreshLayout.isRefreshing() || mRefreshLayout.isLoading()) {
            mRefreshLayout.finishRefresh();
            mRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void requestFailed() {
        boolean isRefreshLayoutWorking = mRefreshLayout != null && (mRefreshLayout.isRefreshing() || mRefreshLayout.isLoading());
        if (isRefreshLayoutWorking) {
            mRefreshLayout.finishRefresh(false);
            mRefreshLayout.finishLoadmore(false);
        }
    }

    @Override
    public void requestHomeContentFailed() {
        if (retryConnectIndexDetail < 5) {
            retryConnectIndexDetail++;
            mPresenter.getHomeContent(uid);
        } else {
            showShortText("请求失败，请检查网络");
            retryConnectIndexDetail = 0;
        }
        boolean isRefreshLayoutWorking = mRefreshLayout != null && (mRefreshLayout.isRefreshing() || mRefreshLayout.isLoading());
        if (isRefreshLayoutWorking) {
            mRefreshLayout.finishRefresh(false);
            mRefreshLayout.finishLoadmore(false);
        }
    }

    private void initEasyPopup() {
        TextView publishDynamic = mEasyPopup.getView(R.id.action_publish_dynamic);
        TextView publishDiscovery = mEasyPopup.getView(R.id.action_publish_discovery);
        TextView publishInterest = mEasyPopup.getView(R.id.action_publish_interest);
        publishDynamic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DynamicPublishActivity.star(mContext);
                mEasyPopup.dismiss();
            }
        });
        publishDiscovery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NewDiscoveryPublishActivity.star(mContext, 1);
                mEasyPopup.dismiss();
            }
        });
        publishInterest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                InterestPublishActivity.star(mContext);
                mEasyPopup.dismiss();
            }
        });
    }

    /**
     * 初始化监听事件
     */
    private void initListener() {
        // 发布按钮点击事件
        btnPublish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String uid = UserInfoBean.getUid(mContext);
                if (TextUtils.isEmpty(uid)) {
                    LoginActivity.star(mContext);
                } else {
                    int i = view.getLayoutParams().width / 2 - DensityUtils.dp2px(mContext, 2);
                    mEasyPopup.showAtAnchorView(view, VerticalGravity.BELOW, HorizontalGravity.ALIGN_RIGHT, i, -DensityUtils.dp2px(mContext, 15));
                }
            }
        });

        // 热门活动的头像点击事件
        hotActiveRvAdapter.setOnAuthorClickListener(new HotActive_RVAdapter.OnAuthorClickListener() {
            @Override
            public void onAuthorClick(View view, int position, HomeBean.DataBean.HotActiveBean bean) {
                String uid = UserInfoBean.getUid(mContext);
                if (TextUtils.isEmpty(uid)) {
                    LoginActivity.star(mContext);
                } else {
                    Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                    intent.putExtra("uid", bean.getUid());
                    startActivity(intent);
                }
            }
        });

        //下拉刷新与上拉加载
        mRefreshLayout.setRefreshHeader(new MyRefreshHeader(mContext));
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        mRefreshLayout.setOnMultiPurposeListener(new OnMultiPurposeListener() {
            @Override
            public void onHeaderPulling(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {
            }

            @Override
            public void onHeaderReleasing(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {
            }

            @Override
            public void onHeaderStartAnimator(RefreshHeader header, int headerHeight, int extendHeight) {
            }

            @Override
            public void onHeaderFinish(RefreshHeader header, boolean success) {
            }

            @Override
            public void onFooterPulling(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterReleasing(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterStartAnimator(RefreshFooter footer, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterFinish(RefreshFooter footer, boolean success) {

            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mPresenter.getHomeList(page);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                hotActiveBeanList.clear();
                mIndexListBeans.clear();
                page = 2;
                mPresenter.getHomeContent(UserInfoBean.getUid(mContext));
            }

            @Override
            public void onStateChanged(RefreshLayout refreshLayout, RefreshState oldState, RefreshState newState) {

            }
        });

        //进入活动页面
        tvActive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), HuoDongActivity.class));
            }
        });

        //进入发现页面
        tvDiscovery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), DiscoveryActivity.class));
            }
        });

        //进入话题页面         ----- 现版本的乐舞
        tvTopic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    Intent intent = new Intent(mContext, WebViewActivity.class);
                    intent.putExtra("url", leWuUrl);
                    startActivity(intent);
                } else {
                    startActivity(new Intent(mContext, LoginActivity.class));
                }
            }
        });

        //进入全部活动
        tvMoreActive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), HuoDongActivity.class));
            }
        });

        ivAttestation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(UserInfoBean.getUid(mContext))) {
                    startActivity(new Intent(mContext, LoginActivity.class));
                } else {
                    String attestAction = UserInfoBean.getAttestation(mContext);
                    Intent intent = new Intent(mContext, IdentificationStatusActivity.class);
                    intent.putExtra("status", attestAction);
                    startActivity(intent);
                }
            }
        });

        hotActiveRvAdapter.setOnItemClickListener(new HotActive_RVAdapter.OnItemClickListener() {
            @Override
            public void onItmClick(View view, int position) {
                Intent intent = new Intent(getActivity(), ActivitiesDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("active", hotActiveBeanList.get(position));
                intent.putExtras(bundle);
                intent.putExtra("active_id", hotActiveBeanList.get(position).getId());
                startActivity(intent);
            }
        });

        homeRvAdapter.setOnItemClickListener(new HomeRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onActiveClick(View view, int position, IndexListBean bean) {
                Intent intent = new Intent(getActivity(), ActivitiesDetailActivity.class);
                intent.putExtra("active_id", bean.getId());
                startActivity(intent);
            }

            @Override
            public void onFreshClick(View view, int position, IndexListBean bean) {
                Intent intent = new Intent(getActivity(), DiscoveryDetailActivity.class);
                intent.putExtra("fresh_id", bean.getId());
                startActivity(intent);
            }

            @Override
            public void onAuthorClick(View view, int position, IndexListBean bean) {
                String authorId = bean.getUserId();
                Intent intent = new Intent(mContext, NewPersonalIndexActivity.class);
                intent.putExtra("uid", authorId);
                startActivity(intent);
            }
        });

        rvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mContext, SearchActivity.class));
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private class MyAMapLocationListener implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    LogUtils.i("位置：" + aMapLocation.getCity(), TAG);
                    mTvLocation.setText(aMapLocation.getCity());
                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    LogUtils.e("AmapError location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo(), TAG);
                    mTvLocation.setText("定位失败");
                }
            }
        }
    }
}
